<?php
namespace modules\post\service;

use idea\saf\sl\Service;
use helper\ErrorNo;
use helper\ErrorMsg;
use helper\Log;

/**
 * Categories class file
 * categories表服务类
 * @author 宋欢 <iphper@yeah.net>
 * @version $Id: categories.php 1 2013-05-18 14:58:59Z huan.song $
 * @package modules.post.service
 * @since 1.0
 */
class Categories extends Service
{
	/**
	 * 添加一条记录
	 * @param array $params
	 * @return array
	 */
	public function add(array $params = array())
	{
		return $this->insert($params, $this->getForm()->getRules());
	}
	
	/**
	 * 更新一条记录
	 * @param integer $id
	 * @param array $params
	 * @return array
	 */
	public function edit($id , array $params = array())
	{
		$this->removeAttributes($params, array('category_name'));
		return $this->updateByPk($id, $params, $this->getForm()->getRules());
	}

	/**
	 * 递归方式获取所有的类别，子类别左边默认用空格填充错位
	 * @param array $params
	 * @param string $leftPad
	 * @param string $rightPad
	 * @param string $padStr
	 * @return array
	 */
	public function findAllByMid(array $params = array(), $leftPad = '', $rightPad = null, $padStr = '&nbsp;&nbsp;&nbsp;&nbsp;')
	{
		$ret = $this->findAllByPidAndMid($params, 'menu_order');
		if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
			return $ret;
		}

		$rows = $ret['data'];
		$data = array();
		foreach ($rows as $key => $row) {
			$tmpLeftPad = is_string($leftPad) ? $leftPad . $padStr : null;
			$tmpRightPad = is_string($rightPad) ? $rightPad . $padStr : null;

			$row['category_name'] = $leftPad . $row['category_name'] . $rightPad;
			$data[] = $row;
			
			$params['category_pid'] = $row['category_id'];
			$ret = $this->findAllByMid($params, $tmpLeftPad, $tmpRightPad, $padStr);
			if ($ret['err_no'] !== ErrorNo::SUCCESS_NUM) {
				return $ret;
			}
			
			$data = array_merge($data, $ret['data']);
		}
		
		return array(
			'err_no' => ErrorNo::SUCCESS_NUM,
			'err_msg' => ErrorMsg::SUCCESS_SELECT,
			'data' => $data
		);
	}
	
	/**
	 * 通过category_pid和module_id获取所有记录，如果module_id为0，则不通过module_id查询
	 * @param array $params
	 * @param string $order
	 * @return array
	 */
	public function findAllByPidAndMid(array $params = array(), $order = '')
	{
		$pid = isset($params['category_pid']) ? (int) $params['category_pid'] : 0;
		$mid = isset($params['module_id']) ? (int) $params['module_id'] : 0;

		if ($pid < 0 || $mid < 0) {
			$errNo = ErrorNo::ERROR_ARGS_SELECT;
			$errMsg = ErrorMsg::ERROR_ARGS_SELECT;
			Log::warning(sprintf(
				'%s category_pid "%s", module_id "%s", params "%s", order "%s"', $errMsg, $pid, $mid, $params, $order
			), $errNo, __METHOD__);
			return array(
				'err_no' => $errNo,
				'err_msg' => $errMsg
			);
		}

		$attributes = array();
		$attributes['category_pid'] = $pid;
		if ($mid > 0) {
			$attributes['module_id'] = $mid;
		}

		return $this->findAllByAttributes($attributes, $order);
	}
}
